#include <iostream>
#include <string.h>
using namespace std;
// len 为字符数组string的总容量
void ReplaceBlank(char str[], int len)
{
    if(str == NULL || len <= 0) return;
    
    int originalLength = 0;
    int numberOfBlank = 0;
    int i = 0;
    while(str[i] != '\0')
    {
        ++originalLength;
        if(str[i] == ' ') ++numberOfBlank;
        i++;
    }

    int newLength = originalLength + numberOfBlank * 2;
    if(newLength > len) return;
    int indexOfOriginal = originalLength;
    int indexOfNew = newLength;

    while(indexOfOriginal >= 0 && indexOfNew > indexOfOriginal)
    {
        if(str[indexOfOriginal] == ' ')
        {
            str[indexOfNew--] = '0';
            str[indexOfNew--] = '2';
            str[indexOfNew--] = '%';
        }
        else
        {
            str[indexOfNew--] = str[indexOfOriginal];
        }
        --indexOfOriginal;
    }
}

int main()
{
    // 含有空格的测试
    char s1[100] = "we are happy";
    ReplaceBlank(s1, 100);
    cout << s1 << endl;
    char s2[100] = " we ";
    ReplaceBlank(s2, 100);
    cout << s2 << endl;
    char s3[100] = " ";
    ReplaceBlank(s3, 100);
    cout << s3 << endl;

    // 不含空格的测试
    char s4[100] = "";
    ReplaceBlank(s4, 100);
    cout << s4 << endl;
    char s5[100] = "we";
    ReplaceBlank(s5, 100);
    cout << s5 << endl;

    // 鲁棒性测试
    char *s6 = NULL;
    ReplaceBlank(s6, 100);
    cout << s6 << endl;

    return 0;
}